package a66weding.com.jiehuntong.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;

import java.util.Random;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.PopGoodsActivity;
import a66weding.com.jiehuntong.activity.StartupActivity;
import a66weding.com.jiehuntong.beans.PushBean;
import a66weding.com.jiehuntong.common.utils.AppUtils;
import a66weding.com.jiehuntong.common.utils.LogUtil;

public class PushReceiver extends BroadcastReceiver {

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public static StringBuilder payloadData = new StringBuilder();
    private NotificationManager notificationManager;
    private String packageName = "a66weding.com.jiehuntong";
    private Gson mGson;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        LogUtil.i("gPush", "onReceive() action=" + bundle.getInt("action"));

        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");

                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");

                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
                LogUtil.i("gPush", "第三方回执接口调用" + (result ? "成功" : "失败"));

                if (payload != null) {
                    String data = new String(payload);
                    LogUtil.i("gPush", "receiver payload : " + data);
                    // 业务
                    if(!TextUtils.isEmpty(data)){
                        mGson = new Gson();
                        try {
                            PushBean pushBean = mGson.fromJson(data, PushBean.class);
                            if(pushBean != null && pushBean.getData() != null){
                                PushBean.DataBean pushData = pushBean.getData();
                                String title = !TextUtils.isEmpty(pushData.getTitle()) ? pushData.getTitle() : "结婚通";
                                String content = pushData.getContent();
                                if (AppUtils.appIsRunning(context, packageName)) {
                                    if (AppUtils.appIsBackgroundRunning(context, packageName)) {
                                        setNotification(context, title, content, pushBean);
                                    } else {
//                                        Toast.makeText(context, content, Toast.LENGTH_LONG).show();
                                        intent = new Intent(context, PopGoodsActivity.class);
                                        intent.putExtra("pushBean", pushBean);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        context.startActivity(intent);
                                    }
                                } else {
                                    setNotification(context, title, content, pushBean);
                                }
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                LogUtil.i("gPush", "cid = " + cid);
                break;
            case PushConsts.GET_SDKONLINESTATE:
                boolean online = bundle.getBoolean("onlineState");
                LogUtil.i("gPush", "online = " + online);
                break;

//            case PushConsts.SET_TAG_RESULT:
//                String sn = bundle.getString("sn");
//                String code = bundle.getString("code");
//
//                String text = "设置标签失败, 未知异常";
//                switch (Integer.valueOf(code)) {
//                    case PushConsts.SETTAG_SUCCESS:
//                        text = "设置标签成功";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_COUNT:
//                        text = "设置标签失败, tag数量过大, 最大不能超过200个";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_FREQUENCY:
//                        text = "设置标签失败, 频率过快, 两次间隔应大于1s";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_REPEAT:
//                        text = "设置标签失败, 标签重复";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_UNBIND:
//                        text = "设置标签失败, 服务未初始化成功";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_EXCEPTION:
//                        text = "设置标签失败, 未知异常";
//                        break;
//
//                    case PushConsts.SETTAG_ERROR_NULL:
//                        text = "设置标签失败, tag 为空";
//                        break;
//
//                    case PushConsts.SETTAG_NOTONLINE:
//                        text = "还未登陆成功";
//                        break;
//
//                    case PushConsts.SETTAG_IN_BLACKLIST:
//                        text = "该应用已经在黑名单中,请联系售后支持!";
//                        break;
//
//                    case PushConsts.SETTAG_NUM_EXCEED:
//                        text = "已存 tag 超过限制";
//                        break;
//
//                    default:
//                        break;
//                }
//
//                LogUtil.i("gPush", "settag result sn = " + sn + ", code = " + code);
//                LogUtil.i("gPush", "settag result sn = " + text);
//                break;
            case PushConsts.THIRDPART_FEEDBACK:
                /*
                 * String appid = bundle.getString("appid"); String taskid =
                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
                 * String result = bundle.getString("result"); long timestamp =
                 * bundle.getLong("timestamp");
                 *
                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid = " +
                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d("GetuiSdkDemo",
                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
                 */
                break;

            default:
                break;
        }
    }

    private void setNotification(Context context, String title, String content, PushBean pushBean) {
        Random r = new Random();
        int notifId = r.nextInt();//随机整数
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notifyIntent = new Intent(context,  StartupActivity.class);
        notifyIntent.putExtra("pushBean", pushBean);
        PendingIntent appIntent = PendingIntent.getActivity(context, notifId,
                notifyIntent, 0);
        Notification.Builder myBuilder = new Notification.Builder(context);
        myBuilder.setContentText(content);
        myBuilder.setContentIntent(appIntent);
        myBuilder.setContentTitle(title);
        myBuilder.setTicker(title);
        myBuilder.setSmallIcon(R.mipmap.logo);
        myBuilder.setAutoCancel(true);
        myBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        notificationManager.notify(notifId, myBuilder.getNotification());
    }
}
